/**
 * 侧边栏组件模块
 * 用于生成统一风格的左侧分类导航栏
 * 支持二级菜单(children)
 */

const SidebarModule = (function () {

  // 数据类型定义
  const DATA_TYPES = ['bank', 'call', 'travel', 'accommodation', 'property', 'railway', 'flight', 'business'];

  // 图标映射
  function getIcon(type) {
    const map = {
      bank: '🏦',
      call: '📱',
      travel: '🚄',
      accommodation: '🏨',
      property: '🏠',
      railway: '🚄',
      flight: '✈️',
      business: '🏢'
    };
    return map[type] || '📄';
  }

  // 名称映射
  function getDataTypeName(type) {
    const map = {
      bank: '银行流水',
      call: '通话记录',
      travel: '出行记录',
      accommodation: '住宿登记',
      property: '不动产登记',
      railway: '铁路售票',
      flight: '飞机售票',
      business: '工商企业'
    };
    return map[type] || type;
  }

  /**
   * 创建侧边栏 HTML（支持二级菜单）
   * @param {string} currentType 当前选中的类型
   * @param {string} clickHandlerName 点击处理函数的名称 (全局函数名)
   * @param {string} title 侧边栏标题
   * @param {Array} customItems (可选) 自定义菜单项列表 [{type, label, icon, children?}]
   * @returns {string} HTML 字符串
   */
  /**
   * 创建侧边栏 HTML（支持二级菜单、徽章、主题）
   * @param {string} currentType 当前选中的类型
   * @param {string} clickHandlerName 点击处理函数的名称 (全局函数名)
   * @param {string} title 侧边栏标题
   * @param {Array} customItems (可选) 自定义菜单项列表 [{type, label, icon, children?, badge?}]
   * @param {string} theme (可选) 'dark' | 'light', 默认 'dark'
   * @returns {string} HTML 字符串
   */
  function createSidebarHtml(currentType, clickHandlerName, title = '分类导航', customItems = null, theme = 'dark') {
    const items = customItems || DATA_TYPES.map(type => ({
      type: type,
      label: getDataTypeName(type),
      icon: getIcon(type),
      children: [] // 默认无子菜单
    }));

    const isLight = theme === 'light';
    const styles = {
      bg: isLight ? '#ffffff' : '#1a1a2e',
      headerBorder: isLight ? '#e6e6e6' : '#16213e',
      text: isLight ? '#303133' : '#ffffff',
      itemText: isLight ? '#606266' : '#a8a8b3',
      itemActiveText: isLight ? '#409eff' : '#4fc3f7',
      itemActiveBg: isLight ? '#ecf5ff' : 'transparent',
      itemActiveBorder: isLight ? '#409eff' : 'transparent',
      subItemText: isLight ? '#606266' : '#808080',
      hoverText: isLight ? '#409eff' : '#ffffff'
    };

    let html = `
      <aside class="sidebar" style="width: 240px; height: 100%; background-color: ${styles.bg}; border-right: 1px solid ${styles.headerBorder}; flex-shrink: 0; overflow-y: auto; display: flex; flex-direction: column;">
        <div class="sidebar-header" style="padding: 15px 20px; border-bottom: 1px solid ${styles.headerBorder};">
          <h3 style="margin: 0; color: ${styles.text}; font-size: 0.95rem;">${title}</h3>
        </div>
        <nav class="sidebar-nav" style="padding: 10px 0; flex: 1;">
    `;

    items.forEach(item => {
      const isActive = currentType === item.type;
      const hasChildren = item.children && item.children.length > 0;
      const isExpanded = hasChildren; // 默认展开所有分类

      // 渲染父级菜单项（一级分类）
      if (hasChildren) {
        // 有子菜单的分类项 - 添加折叠箭头和更明显的样式
        html += `
          <div class="sidebar-category ${isActive ? 'active' : ''}" 
               data-type="${item.type}"
               data-has-children="true"
               onclick="${clickHandlerName}('${item.type}')"
               style="padding: 14px 20px; cursor: pointer; 
                      color: ${isActive ? styles.itemActiveText : styles.itemText}; 
                      background: ${isActive ? styles.itemActiveBg : 'transparent'};
                      border-left: 4px solid ${isActive ? styles.itemActiveBorder : 'transparent'};
                      display: flex; align-items: center; justify-content: space-between; 
                      transition: all 0.2s; font-weight: ${isActive ? 'bold' : '600'}; 
                      border-bottom: 1px solid ${isLight ? '#f0f0f0' : '#2a2a3e'};"
               onmouseover="if(!this.classList.contains('active')) this.style.background='${isLight ? '#f5f7fa' : '#222238'}'"
               onmouseout="if(!this.classList.contains('active')) this.style.background='transparent'">
            <div style="display:flex; align-items:center; gap:10px;">
              <span style="font-size: 1.2rem;">${item.icon}</span>
              <span style="font-size: 0.95rem;">${item.label}</span>
            </div>
            <div style="display:flex; align-items:center; gap:8px;">
              ${item.badge ? `<span class="badge" id="badge-${item.type}" style="font-size:12px; padding:2px 6px; border-radius:10px; background:#f56c6c; color:white; display:none;"></span>` : ''}
              <span class="expand-icon" onclick="event.stopPropagation(); window.SidebarModule.toggleCategory('${item.type}')" 
                    style="cursor:pointer; font-size:12px; color:${styles.itemText}; transition: transform 0.2s; transform: rotate(${isExpanded ? '90deg' : '0deg'});">
                ▶
              </span>
            </div>
          </div>
        `;

        // 渲染子菜单容器（二级分类）
        html += `<div class="sidebar-children" data-parent="${item.type}" style="display:${isExpanded ? 'block' : 'none'}; background:${isLight ? '#fafbfc' : '#1a1a28'};">`;

        item.children.forEach(child => {
          const isChildActive = currentType === child.type;
          html += `
            <div class="sidebar-subitem ${isChildActive ? 'active' : ''}"
                 data-type="${child.type}"
                 onclick="event.stopPropagation(); ${clickHandlerName}('${child.type}')"
                 style="padding: 10px 20px 10px 52px; cursor: pointer; 
                        color: ${isChildActive ? styles.itemActiveText : styles.subItemText}; 
                        background: ${isChildActive ? styles.itemActiveBg : 'transparent'};
                        border-left: 4px solid ${isChildActive ? styles.itemActiveBorder : 'transparent'};
                        font-size: 0.85rem; transition: all 0.2s; 
                        display:flex; justify-content:space-between; align-items:center;"
                 onmouseover="if(!this.classList.contains('active')) { this.style.color='${styles.hoverText}'; this.style.background='${isLight ? '#ecf5ff' : '#1e1e2e'}'; }"
                 onmouseout="if(!this.classList.contains('active')) { this.style.color='${styles.subItemText}'; this.style.background='transparent'; }">
              <span>${child.name || child.label}</span>
              <span class="badge" id="badge-${child.id || child.type}" style="font-size:12px; padding:2px 6px; border-radius:10px; background:#f56c6c; color:white; display:none;"></span>
            </div>
          `;
        });

        html += `</div>`; // 关闭子菜单容器
      } else {
        // 没有子菜单的独立项（如"总览仪表盘"）
        html += `
          <div class="sidebar-item ${isActive ? 'active' : ''}" 
               data-type="${item.type}"
               onclick="${clickHandlerName}('${item.type}')"
               style="padding: 14px 20px; cursor: pointer; color: ${isActive ? styles.itemActiveText : styles.itemText}; 
                      background: ${isActive ? styles.itemActiveBg : 'transparent'};
                      border-left: 4px solid ${isActive ? styles.itemActiveBorder : 'transparent'};
                      display: flex; align-items: center; justify-content: space-between; transition: all 0.2s;
                      border-bottom: 1px solid ${isLight ? '#f0f0f0' : '#2a2a3e'};"
               onmouseover="if(!this.classList.contains('active')) this.style.color='${styles.hoverText}'"
               onmouseout="if(!this.classList.contains('active')) this.style.color='${styles.itemText}'">
            <div style="display:flex; align-items:center; gap:10px;">
              <span style="font-size: 1.1rem;">${item.icon}</span>
              <span style="font-size: 0.9rem; font-weight: ${isActive ? 'bold' : 'normal'}">${item.label}</span>
            </div>
            ${item.badge ? `<span class="badge" id="badge-${item.type}" style="font-size:12px; padding:2px 6px; border-radius:10px; background:#f56c6c; color:white; display:none;"></span>` : ''}
          </div>
        `;
      }
    });

    html += `
        </nav>
      </aside>
    `;

    return html;
  }

  /**
   * 切换分类的展开/折叠状态
   */
  function toggleCategory(categoryType) {
    const childrenContainer = document.querySelector(`.sidebar-children[data-parent="${categoryType}"]`);
    const expandIcon = document.querySelector(`.sidebar-category[data-type="${categoryType}"] .expand-icon`);

    if (childrenContainer && expandIcon) {
      const isExpanded = childrenContainer.style.display !== 'none';
      childrenContainer.style.display = isExpanded ? 'none' : 'block';
      expandIcon.style.transform = isExpanded ? 'rotate(0deg)' : 'rotate(90deg)';
    }
  }

  /**
   * 更新侧边栏选中状态
   * @param {HTMLElement} container 包含侧边栏的容器
   * @param {string} newType 新选中的类型
   */
  /**
   * 更新侧边栏选中状态
   * @param {HTMLElement} container 包含侧边栏的容器
   * @param {string} newType 新选中的类型
   * @param {string} theme (可选) 'dark' | 'light', 默认 'dark'
   */
  function updateSelection(container, newType, theme = 'dark') {
    if (!container) return;

    const isLight = theme === 'light';
    const styles = {
      itemText: isLight ? '#606266' : '#a8a8b3',
      itemActiveText: isLight ? '#409eff' : '#4fc3f7',
      itemActiveBg: isLight ? '#ecf5ff' : 'transparent',
      itemActiveBorder: isLight ? '#409eff' : 'transparent',
      subItemText: isLight ? '#606266' : '#808080'
    };

    // 查找容器内的所有 sidebar-item, sidebar-subitem 和 sidebar-category
    const items = container.querySelectorAll('.sidebar-item, .sidebar-subitem, .sidebar-category');

    items.forEach(item => {
      // 检查是否是当前选中项 (支持父级和子级)
      // 注意：这里简化处理，只高亮完全匹配的 type
      const type = item.dataset.type;
      const isSubItem = item.classList.contains('sidebar-subitem');

      if (type === newType) {
        item.classList.add('active');
        item.style.color = styles.itemActiveText;
        item.style.fontWeight = 'bold';
        if (isLight) {
          item.style.background = styles.itemActiveBg;
          item.style.borderLeftColor = styles.itemActiveBorder;
        }
      } else {
        item.classList.remove('active');
        item.style.color = isSubItem ? styles.subItemText : styles.itemText;
        item.style.fontWeight = 'normal';
        if (isLight) {
          item.style.background = 'transparent';
          item.style.borderLeftColor = 'transparent';
        }
      }
    });
  }

  return {
    createSidebarHtml,
    updateSelection,
    toggleCategory,
    getIcon,
    getDataTypeName
  };

})();

// 暴露给全局
window.SidebarModule = SidebarModule;
